<?php
namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\MemberInterface;
use App\Repository\Contracts\MemberJavaInterface;
use App\Support\Helper\CommonHelper;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-16 14:41
 *
 * @Description:
 */
class MemberRepository extends Repository implements MemberInterface
{
    protected $rules = [
        'created' => [
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/|unique:member,phone',
            'number' => 'required|min:8|max:32|unique:member,number',
            'real_name' => 'sometimes|min:2|max:10'
        ],
        'updated' => [
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/|unique:member',
            'number' => 'required|min:8|max:32|unique:member',
            'real_name' => 'sometimes|min:2|max:10'
        ]
    ];

    protected $messages = [
        'phone.required' => '手机号码不能为空',
        'phone.regex' => '手机号码不合法',
        'phone.unique' => '手机号码已存在',
        'number.required' => "会员卡号不能为空",
        'number.min' => "会员卡号不能少于8个字",
        'number.max' => "会员卡号不能多于32个字",
        'number.unique' => "会员卡号已存在",
        'real_name.required' => "真实姓名不能为空",
        'real_name.min' => "真实姓名不能少于2个字",
        'real_name.max' => "真实姓名不能多于10个字"
    ];

    protected function modelName()
    {
        return 'App\Model\Member';
    }

    public function lists($limit, $page, $map = [])
    {
        $query = $this->searchMap($map);
        $total = $query->count();
        $list = $query->orderBy('uid', 'desc')->simplePaginate($limit, ['*'], 'page', $page);

        return $this->simplePaginate('list', $list->items(), $total, ceil($total / $limit), $page);
    }

    public function detail($uid, $isLocal = false)
    {
        if (env('DIRECT_SALE') && !$isLocal && env('JAVA_NETWORK')) {
            $result = $this->container->make(MemberJavaInterface::class)->findById($uid);
            if (!$result) {
                throw new ValidateException('会员不存在');
            }
            if ($result['resultType'] === 'success') {
                return [
                    'integral' => round($result['resultData']['merPoints'], 2),
                    'money' => round($result['resultData']['merBal'], 2),
                    'number' => $result['resultData']['merCardNo'],
                    'phone' => $result['resultData']['merPhone'],
                    'real_name' => $result['resultData']['merRealName'],
                    'uid' => $result['resultData']['id'],
                    'created_at' => $result['resultData']['createDate']
                ];
            }

            throw new ValidateException('当前处于离线状态,请稍后');
        }
        $data = $this->findBy('uid', $uid);

        return $data ? $data->toArray() : false;
    }

    public function findByPhone($phone)
    {
        if (env('DIRECT_SALE') && env('JAVA_NETWORK')) {
            $result = $this->container->make(MemberJavaInterface::class)->findByPhone($phone);
            if (!$result) {
                throw new ValidateException('会员不存在');
            }
            if ($result['resultType'] === 'success') {
                return [
                    'integral' => round($result['resultData']['merPoints'], 2),
                    'money' => round($result['resultData']['merBal'], 2),
                    'number' => $result['resultData']['merCardNo'],
                    'phone' => $result['resultData']['merPhone'],
                    'real_name' => $result['resultData']['merRealName'],
                    'uid' => $result['resultData']['id'],
                    'created_at' => $result['resultData']['createDate']
                ];
            }

            throw new ValidateException('当前处于离线状态,请稍后');
        }
        $data = $this->findBy('phone', $phone);

        return $data ? $data->toArray() : false;
    }

    public function findByNumber($number)
    {
        if (env('DIRECT_SALE') && env('JAVA_NETWORK')) {
            $result = $this->container->make(MemberJavaInterface::class)->findByNumber($number);
            if (!$result) {
                throw new ValidateException('会员不存在');
            }
            if ($result['resultType'] === 'success') {
                return [
                    'integral' => round($result['resultData']['merPoints'], 2),
                    'money' => round($result['resultData']['merBal'], 2),
                    'number' => $result['resultData']['merCardNo'],
                    'phone' => $result['resultData']['merPhone'],
                    'real_name' => $result['resultData']['merRealName'],
                    'uid' => $result['resultData']['id'],
                    'created_at' => $result['resultData']['createDate']
                ];
            }

            throw new ValidateException('当前处于离线状态,请稍后');
        }
        $data = $this->findBy('number', $number);

        return $data ? $data->toArray() : false;
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');
        $data['salt'] = str_random(6);
        $data['password'] = CommonHelper::hashPassword($data['salt'], str_random(8));
        if (env('DIRECT_SALE') && env('JAVA_NETWORK')) {
            $result = $this->container->make(MemberJavaInterface::class)->syncCreated($data['store_id'], $data);
            if ($result['resultType'] === 'success') {
                $data['uid'] = $result['resultData'];
                return $this->save($data);
            }

            throw new ValidateException('当前处于离线状态,请稍后');
        }
        // TODO $this->container->make(MessageService::class)->sendMessage($user->phone, 1);
        $lastId = $this->save($data);
        $lastId && $this->update(['uid' => $lastId], $lastId, 'id');

        return $lastId;
    }

    public function updated($id, array $data)
    {
        $this->validate($data, 'updated', ['phone' => $id, 'number' => $id]);
        if (env('DIRECT_SALE') && env('JAVA_NETWORK')) {
            $uid = $this->find($id, ['uid'])->toArray()['uid'];
            if ($this->container->make(MemberJavaInterface::class)->syncUpdated($uid, $data))
                return $this->update($data, $id, 'id');

            throw new ValidateException('当前处于离线状态,请稍后');
        }

        return $this->update($data, $id, 'id');
    }

    public function findIdForFirst()
    {
        return $this->model->orderBy('updated_at', 'desc')->limit(1)->get()->toArray();
    }

    public function updateIntegral($uid, $integral)
    {
        return $this->model->where('uid', '=', $uid)->increment('integral', $integral);
    }

    public function updateMoney($uid, $money)
    {
        return $this->model->where('uid', '=', $uid)->increment('money', $money);
    }
}